use actix_web::rt::Runtime;
use actix_web::{get, post, web, App, HttpResponse, HttpServer, Responder, Result};
use serde::Deserialize;
use std::sync::{Arc, Mutex};
use std::thread;
use tauri::async_runtime::RwLock;
use tauri::Manager;

pub struct WebService {
    port: u16,
    host: String,
    paused: RwLock<bool>,
}

impl WebService {
    pub fn new(port: u16, host: String) -> WebService {
        WebService {
            port,
            host,
            paused: RwLock::new(false),
        }
    }

    pub fn start(self, app_handle: tauri::AppHandle) {
        thread::spawn(move || {
            let rt = Runtime::new().unwrap();
            rt.block_on(async move {
                HttpServer::new(|| App::new().service(hello).service(scan))
                    .bind((self.host, self.port))?
                    .run()
                    .await
            })
            .unwrap();
        });
    }
}

#[get("/")]
async fn hello() -> impl Responder {
    HttpResponse::Ok().body("Hello world!")
}

#[post("/api/ScanInfo/Index")]
async fn scan(scan: web::Json<ScanInfo>) -> Result<String> {
    Ok(format!("{}", scan.code))
}

#[derive(Deserialize)]
struct ScanInfo {
    pub code: String,
}
